import mqtt from 'mqtt'
import config from '@/config'
import store from '@/store'

// 设备管理业务消息

/** FOTA升级执行进度 */
const FOTA_PROCESS = 'vrich/afs/fota/process'

/** 移纤业务执行进度 */
const TRANSFER_PROCESS = 'vrich/afs/transfer/process'

/** OTDR测试业务执行进度 */
const OTDR_TEST_PROCESS = 'vrich/afs/otdrTest/process'

/** OTDR测试结果 */
const OTDR_TEST_RESULT = 'vrich/afs/otdrTest/result'

/** OTDR测试业务执行进度 */
const LIGHT_TEST_PROCESS = 'vrich/afs/lightTest/process'

/** 光功率测试结果 */
const LIGHT_TEST_RESULT = 'vrich/afs/lightTest/result'

/** 光纤拔插进度 */
const UNPLUG_PROCESS = 'vrich/afs/unplug/process'

/** 视频调控状态 */
const OUTER_RING = 'vrich/afs/state'

/** 视频调控订阅脉冲状态 */
const REGULATE_STATE = 'vrich/afs/regulate/state'

/** 告警新增 */
const ALARM_ADD = 'vrich/biz/alarm/add'

/** 告警结束 */
const ALARM_OVER = 'vrich/biz/alarm/over'

/** 设备自检进度 */
const SELF_CHECK_PROGRESS = 'vrich/afs/self/check/process'

/** MQTT连接信息 */
const { service, username, password } = config.mqtt

/** MQTT客户端 */
const client = mqtt.connect(service, { username, password })

/** 建立连接后订阅Topic */
client.on('connect', () => {
  console.log('mqtt连接成功')
  client.subscribe('vrich/#')
})

client.on('error', () => {
  console.log('mqtt连接失败')
})

/** 收到消息后进行消息分发到Store */
client.on('message', (topic, message) => {
  try {
    console.log(topic + ' ==> ' + message)
    const data = JSON.parse(message.toString())
    switch (topic) {
      case FOTA_PROCESS:
        console.log(topic + ' ==> ' + message)
        store.commit('setFotaProcess', data)
        break
      case TRANSFER_PROCESS:
        store.commit('setTransferProcess', data)
        break
      case OTDR_TEST_PROCESS:
        store.commit('setOtdrTestProcess', data)
        break
      case OTDR_TEST_RESULT:
        store.commit('setOtdrTestResult', data)
        break
      case LIGHT_TEST_PROCESS:
        store.commit('setLightTestProcess', data)
        break
      case LIGHT_TEST_RESULT:
        store.commit('setLightTestResult', data)
        break
      case ALARM_ADD:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('SETALARM_ADD', data)
        break
      case ALARM_OVER:
        console.log(topic + ' ==> ' + message.toString())
        store.commit('ALARM_REMOVE', data)
        break
      case UNPLUG_PROCESS:
        console.log(data)
        store.commit('setUnplugProcess', data)
        break
      case OUTER_RING:
        store.commit('setVideoCtrInfos', data)
        break
      case REGULATE_STATE:
        store.commit('setVideoAfsStateInfo', data)
        break
      case SELF_CHECK_PROGRESS:
        store.commit('setSelfCheckProgress', data)
        break
      default:
        break
    }
  } catch (error) {
    console.log(error)
  }
})

export default client
